//
//  LoginViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/2/27.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "LoginViewController.h"
#import "loginView.h"
#import "RegisterViewController.h"
#import "FindPwdViewController.h"
#import "ETCommon.h"
#import "AppDelegate.h"
#import "LoginModelPack.h"
#import "TabBarController.h"
#import "PCCircleViewConst.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)LoginView *lv;

@end

@implementation LoginViewController

#pragma mark 初始化
-(void)loadView{
    [super loadView];
    self.lv = [[LoginView alloc] initWithFrame:self.view.bounds];
    self.view = self.lv;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSDictionary *dic = [AppTools getUserNameAndPwd];
    self.lv.passwordTF.text = @"";
    self.lv.phonoNumTf.text = @"";
    [self.lv.phonoNumTf insertText:dic[@"userName"]];
    [self.lv.passwordTF insertText:dic[@"userPwd"]];
    
    
    //清除指纹验证
    /*
    if (self.type == LoginVCFromFingerfrintVerifyVC) {
        [PCCircleViewConst saveFingerprint:nil Key:fingerprintStatueKey];
    }
     */
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    //创建左按钮
    [self createLeftBtn];
    //跳转注册
    [self.lv.registerBtn addTarget:self action:@selector(registerBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.lv.registerImv.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registerBtnAction)];
    [self.lv.registerImv addGestureRecognizer:tap];
    //忘记密码
    [self.lv.findPwdBtn addTarget:self action:@selector(findPwdBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //登录按钮
    [self.lv.loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //记住密码
    [self.lv.radioBtn addTarget:self action:@selector(radioBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //手机号、密码符合规则,可以点击登录
    [self.lv.phonoNumTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    [self.lv.passwordTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    //设置密码输入框代理(点击完成退出键盘)
    self.lv.passwordTF.delegate = self;
    
}

-(void)textFieldDidChange :(UITextField *)textField{
    
    //手机号输入框只能输入11位
    if (textField == self.lv.phonoNumTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    
    
    
    if (self.lv.phonoNumTf.text.length > 0 && self.lv.passwordTF.text.length > 0) {
        self.lv.loginBtn.backgroundColor = ETCONFIRMCOLOR;
        self.lv.loginBtn.userInteractionEnabled = YES;
    }else
    {
        self.lv.loginBtn.backgroundColor = ETCOMMONCOLOR;
        self.lv.loginBtn.userInteractionEnabled = NO;
    }
    
}


-(void)radioBtnAction
{
    self.lv.radioBtn.selected = !self.lv.radioBtn.selected;
}



-(void)loginBtnAction
{
    //点击登录   退键盘
    [self.view endEditing:YES];
    
    
    if (![AppTools validateMobile:self.lv.phonoNumTf.text]) {
        [self showFailedResultTips:@"请填写正确的手机号格式" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    /*
    if (![AppTools checkPassword:self.lv.passwordTF.text]) {
        [self showFailedResultTips:@"请填写正确的密码格式" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
     */
    

    if (self.lv.radioBtn.selected) {
        //记住密码保存在本地
        [AppTools saveUserAndPwd:self.lv.phonoNumTf.text Pwd:self.lv.passwordTF.text];
    }else
    {
       //不做处理
    }
  
    LoginRequest *request = [[LoginRequest alloc] init];
    request.loginName = self.lv.phonoNumTf.text;
    request.passWord = [self.lv.passwordTF.text md5];
    NSDictionary *dic = [request mj_keyValues];
     NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/login/loginA0100"];
    __weak __typeof(self) weakSelf = self;
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [weakSelf loginSuccessWithResponse:responseObject];
        }
    } FailedHandler:^(NSError *error) {
        
        NSLog(@"%@",error.localizedDescription);
    }];
    
}
//登录成功跳转
-(void)loginSuccessWithResponse:(id )responseObject
{
    
    //判断是否为同一账号
    NSString *loginName = [[NSUserDefaults standardUserDefaults] valueForKey:@"loginName"];
    if ([self.lv.phonoNumTf.text isEqualToString:loginName]) {
        //和上次登录的为同一账户  不做处理
    }else
    {
        //清除手势指纹状态
        [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
        [PCCircleViewConst saveFingerprint:nil Key:fingerprintStatueKey];
    }
    
    NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
    //解析数据
    NSDictionary *dic = [responseObject mj_JSONObject];
    LoginResponse *loginResponse = [LoginResponse mj_objectWithKeyValues:dic];
    [AppTools shareInstance].userInfo = loginResponse.response.userInfo;
    [AppTools shareInstance].msgInfo = loginResponse.response.msgInfo;
    //登录成功保存用户名用于区分是不是登录了同一个账户
    [[NSUserDefaults standardUserDefaults] setObject:loginResponse.response.userInfo.loginName forKey:@"loginName"];
    
    /*
    //如果是验证手势页面错误5次  清除手势信息和手势错误次数
    if (self.type == LoginVCFromGesterVerifyVC) {
        [AppTools setGesterWrongTimes:0];
        [PCCircleViewConst saveGesture:nil Key:gestureFinalSaveKey];
    }
     */
    
    
    
    /*
    //把登录返回的数据模型存储到本地
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:loginResponse.response.userInfo];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"u"];
     */
    
    //登录成功   更新在本地保存的token
    [AppTools setToken:loginResponse.response.auth_token];
    
    //记录登录状态
    [AppTools saveLoginStatus:YES];
    
    if (self.type == LoginVCFromFingerfrintVerifyVC || self.type == LoginVCFromGesterVerifyVC) {
        TabBarController *tabVC = [[TabBarController alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
    }else
    {
        /*
        [self showSuccessResultTips:@"登录成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
         */
        TabBarController *tabVC = [[TabBarController alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
    }
}

-(void)findPwdBtnAction
{
    FindPwdViewController *findVC = [[FindPwdViewController alloc] init];
    [self.navigationController pushViewController:findVC animated:YES];
}
-(void)registerBtnAction
{
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
}

-(void)createLeftBtn
{
    UIButton *leftBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.frame = CGRectMake(0, 0, 22, 22);
    [leftBtn addTarget:self action:@selector(leftBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    [leftBtn setImage:[UIImage imageNamed:@"nav_icon_arrow_x"] forState:(UIControlStateNormal)];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    if (self.type == LoginVCFromFingerfrintVerifyVC || self.type == LoginVCFromGesterVerifyVC) {
        self.navigationItem.leftBarButtonItem.customView.hidden = YES;
    }else
    {
        self.navigationItem.leftBarButtonItem.customView.hidden = NO;
    }
}
-(void)leftBtnAction
{
    NSLog(@"点击左上方退出");
    [AppTools saveLoginStatus:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    [self.lv.phonoNumTf resignFirstResponder];
    [self.lv.passwordTF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    return YES;
}

@end
